/*
 * Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *   This program uses the Content API for Shopping to insert, query, update,
 *   and delete items in Merchant Center using the raw XML protocol.  The
 *   specific implementation is in java but the raw protocol can be implemented
 *   in any language.
 * 
 *   All operations requires a Google ClientLogin token (from ClientLogin.java)
 *   which may be reused.
 *   
 *   Usage:
 *   ClientAPITests -operation= -merchant_id= -username= 
 *   				       -password= -file= -offer_id=
 *   
 *   java -cp . ContentAPITests -operation=insert 
 *   				-merchant_id=your_merchant_id 
 *   				-username=your_merchant_gmail@gmail.com 
 *   				-password=your_password 
 *   				-file=insert.xml 
 *   				-offer_id=online:en:US:1022316

 *   
 *     cid=  your merchantID
 *     username = merchant center username
 *     passwd = merchant center password
 *     file= query|insert|update|delete|batch
 *     itemid = if query, then its the item
 *  
 *   edit merchant_id= with your merchant center ID
 *   edit merchant_uname, merchant_passwd with your merchant username/password
 *   
 *   Insert:
 *   	Edit insert.xml, change  
 *   	link rel="alternate" type="text/html" and insert your own URL
 *   	This operation will insert an item with the GCS usecase only with
 *   	with 
 *   	<sc:id>1022316</sc:id>
 *   	<scp:price unit="usd">125</scp:price>
 *   
 *   Update:
 *   	Edit update.xml change
 *   	link rel="alternate" type="text/html" and insert your own URL
 *   	This operation will update item ID=1022316 with a new price $225.
 *   	Note:  you must provide the full product listing in addition to the
 *   	updated fields for this operation (i.e, not just the incremental or 
 *   	delta updates).
 *   
 *   Delete:
 *   	This operation will delete an item ID=1022316 for merchant=123456
 *      i.e, URL  id=online:en:US:1022316
 *      /feeds/123456/items/products/schema/1022316
 *   
 *   Batch:
 *   	Edit batch.xml
 *   	This operation will insert item <sc:id>1022316</sc:id> and
 *   	delete item with ID=44 in one call
 *   	/feeds/123456/items/products/schema/44
 *   	The response stream is a status update for each operation in the batch.
 *   	
 *   Query:
 *   	This is a basic ContentAPI query which will just recall the last
 *   	inserted content (i.e, what was last inserted/updated, etc).  
 *   	Note:  the recalled item is *not* necessarily the version that is 
 *   	being served because the current item may be pending serving.
 *   	You can use the query to see the current 'state' of an item that
 *   	(at that time atleast) is serving or pending publishing.
 *   
 *   see 
 *   http://code.google.com/apis/shopping/content/
 *   http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
 *   http://code.google.com/apis/shopping/content/developers_guide_java.html
 *   
 */

public class ContentAPITests {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String merchant_id ="";
		String username = "";
		String password = "";
		String operation = "";
		String file = "";
		String offer_id = "";
		
		if (args.length < 5)
		{
			ContentAPITests.printUsage();
			System.exit(-1);
		}
		
		for (String a :args)
		{
			if (a.startsWith("-operation="))
				operation = a.split("=")[1];
			if (a.startsWith("-merchant_id="))
				merchant_id = a.split("=")[1];	
			if (a.startsWith("-username="))
				username = a.split("=")[1];	
			if (a.startsWith("-password="))
				password = a.split("=")[1];	
			if (a.startsWith("-file="))
				file = a.split("=")[1];	
			if (a.startsWith("-offer_id="))
				offer_id = a.split("=")[1];				
		}
		
		if (operation.equals("") || merchant_id.equals("") ||
					username.equals("") || password.equals(""))
			System.out.println("Provide values for merchant_id, username," + 
						"password, operation");	
		else
		{
			ContentAPITests sc = new ContentAPITests(merchant_id,username, 
								password,operation,file, offer_id);
		}
	}
	
	private static void printUsage()
	{
		System.out.println("Usage ContentAPITests ");
		System.out.println("  -operation= query|insert|update|delete|batch");
		System.out.println("  -merchant_id= merchant center ID");
		System.out.println("  -username= merchant center username");
		System.out.println("  -password= merchant center password");
		System.out.println("  -file=");
		System.out.println("  -offer_id= (for query,delete,update");
	}
	
	public ContentAPITests(String merchant_id, String merchant_uname,
						String merchant_passwd, String operation,
						String file, String offer_id)
	{
		try
		{
			
			ClientLogin cl = new ClientLogin(merchant_uname,merchant_passwd,
											"structuredcontent");
			String token = cl.authenticate();
			System.out.println("Acquired Auth Token--> " + token);

			if (operation.equalsIgnoreCase("query"))
			{
				if (offer_id.equals(""))
					System.out.println("offer_id cannot be null");
				else
					query(merchant_id,token,offer_id);
			}
			else if(operation.equalsIgnoreCase("insert"))
			{
				if (offer_id.equals("") || file.equals(""))
					System.out.println("offer_id/file cannot be null");
				else
				{
					FileInputStream fis = new FileInputStream(file);		
					insert(merchant_id,token,fis);	
				}
			}
			else if(operation.equalsIgnoreCase("update"))
			{
				if (offer_id.equals("") || file.equals(""))
					System.out.println("offer_id/file cannot be null");
				else
				{
					FileInputStream fis = new FileInputStream(file);		
					update(merchant_id,token,fis, offer_id);	
				}
			}	
			else if(operation.equalsIgnoreCase("delete"))
			{
				if (offer_id.equals(""))
					System.out.println("offer_id cannot be null for delete");
				else
					delete (merchant_id,token,offer_id);	
			}				
				
			else if(operation.equalsIgnoreCase("batch"))
			{
				if (file.equals(""))
					System.out.println("file cannot be null for batch");
				else
				{
					FileInputStream fis = new FileInputStream(file);
					batch (merchant_id,token,fis);	
				}
			}				
			
		}
		catch (Exception ex) 
		{
			System.out.println("Error " +ex);
		}
	}
	  
	  private void insert(String merchant_id, String auth_token, InputStream feed_stream) throws IOException {

			String INSERT_FEED = "https://content.googleapis.com/content/v1/"+ merchant_id + "/items/products/schema";
		    HttpURLConnection connection = (HttpURLConnection)(new URL(INSERT_FEED)).openConnection();    
		    connection.setDoInput(true);
		    connection.setDoOutput(true);
		    connection.setRequestMethod("POST");
		    connection.setRequestProperty("Content-Type", "application/atom+xml");
		    connection.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);

		    OutputStream outputStream = connection.getOutputStream();
		    byte[] buf = new byte[1024];
		    int numRead;
		    while ( (numRead = feed_stream.read(buf) ) >= 0) {
		    	outputStream.write(buf, 0, numRead);
		    }    
		    outputStream.close();
		  
		    int responseCode = connection.getResponseCode();
		    System.out.println("HTTP RESPONSE CODE: " + responseCode);
		    InputStream inputStream;
		    if (responseCode == HttpURLConnection.HTTP_CREATED) {
		      inputStream = connection.getInputStream();
		    } else {
		      inputStream = connection.getErrorStream();
		    }
		    System.out.println(toString(inputStream));
		  }
	  
	  private void update(String merchant_id, String auth_token, InputStream feed_stream,String offer_id) throws IOException {
		    String UPDATE_FEED = "https://content.googleapis.com/content/v1/"+ merchant_id + "/items/products/schema/" + offer_id;
		    
		    HttpURLConnection connection = (HttpURLConnection)(new URL(UPDATE_FEED)).openConnection();    
		    connection.setDoInput(true);
		    connection.setDoOutput(true);
	    	connection.setRequestMethod("PUT");		    
		    connection.setRequestProperty("Content-Type", "application/atom+xml");
		    connection.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);		    

		    OutputStream outputStream = connection.getOutputStream();
		    byte[] buf = new byte[1024];
		    int numRead;
		    while ( (numRead = feed_stream.read(buf) ) >= 0) {
		    	outputStream.write(buf, 0, numRead);
		    }    
		    outputStream.close();
		  
		    // Retrieve the output
		    int responseCode = connection.getResponseCode();
		    System.out.println("HTTP RESPONSE CODE: " + responseCode);
		    InputStream inputStream;
		    if (responseCode == HttpURLConnection.HTTP_OK) {
		      inputStream = connection.getInputStream();
		    } else {
		      inputStream = connection.getErrorStream();
		    }
		    
		    // write the output to the console
		    System.out.println(toString(inputStream));
		  }	  
	  
	  private void delete(String merchant_id, String auth_token, String offer_id) throws IOException {
			String DELETE = "https://content.googleapis.com/content/v1/"+ merchant_id + "/items/products/schema/" + offer_id;
		    HttpURLConnection connection = (HttpURLConnection)(new URL(DELETE)).openConnection();    
		    connection.setDoInput(true);
		    connection.setDoOutput(true);
		    connection.setRequestMethod("DELETE");
		    connection.setRequestProperty("Content-Type", "application/atom+xml");
		    connection.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);
		    
		    // Retrieve the output
		    int responseCode = connection.getResponseCode();
		    System.out.println("HTTP RESPONSE CODE: " + responseCode);
		    InputStream inputStream;
		    if (responseCode == HttpURLConnection.HTTP_OK) {
		      inputStream = connection.getInputStream();
		    } else {
		      inputStream = connection.getErrorStream();
		    }
		    
		    System.out.println(toString(inputStream));
		  }	  
	    
	  private void batch(String merchant_id, String auth_token, InputStream feed_stream) throws IOException {

		    String BATCH_FEED = "https://content.googleapis.com/content/v1/"+ merchant_id + "/items/products/schema/batch";
		    HttpURLConnection connection = (HttpURLConnection)(new URL(BATCH_FEED)).openConnection();    
		    connection.setDoInput(true);
		    connection.setDoOutput(true);
		    connection.setRequestMethod("POST");
		    connection.setRequestProperty("Content-Type", "application/atom+xml");
		    connection.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);
		  
		    OutputStream outputStream = connection.getOutputStream();
		    byte[] buf = new byte[1024];
		    int numRead;
		    while ( (numRead = feed_stream.read(buf) ) >= 0) {
		    	outputStream.write(buf, 0, numRead);
		    }    
		    outputStream.close();
		  
		    int responseCode = connection.getResponseCode();
		    System.out.println("HTTP RESPONSE CODE: " + responseCode);
		    InputStream inputStream;
		    if (responseCode == HttpURLConnection.HTTP_OK) {
		      inputStream = connection.getInputStream();
		    } else {
		      inputStream = connection.getErrorStream();
		    }
		    System.out.println(toString(inputStream));
		  }
	    
	  private void query(String merchant_id, String auth_token, String offer_id) throws IOException {
		  
			String query = "https://content.googleapis.com/content/v1/"+ merchant_id + "/items/products/schema/" + offer_id;
		    HttpURLConnection connection = (HttpURLConnection)(new URL(query)).openConnection();  
		    connection.setDoInput(true);
		    connection.setDoOutput(true);
		    connection.setRequestMethod("GET");
		    connection.setRequestProperty("Content-Type", "application/atom+xml");
		    connection.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);
		    connection.connect();
		    
		    // Retrieve the output
		    int responseCode = connection.getResponseCode();
		    System.out.println("HTTP RESPONSE CODE: " + responseCode);
		    
		    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		    StringBuilder  stringBuilder = new StringBuilder();

		      String line = null;
		      while ((line = reader.readLine()) != null)
		      {
		        stringBuilder.append(line + "\n");
		      }
		      System.out.println(stringBuilder.toString());

		      
		    InputStream inputStream;
		    if (responseCode == HttpURLConnection.HTTP_OK) {
		      inputStream = connection.getInputStream();
		    } else {
		      inputStream = connection.getErrorStream();
		    }
		    System.out.println(toString(inputStream));
		    connection.disconnect();
		    inputStream.close();
		    reader.close();


		  }	  
	  
	  private String toString(InputStream inputStream) throws IOException {
		    String string;
		    StringBuilder outputBuilder = new StringBuilder();
		    if (inputStream != null) {
		      BufferedReader reader =
		          new BufferedReader(new InputStreamReader(inputStream));
		      while (null != (string = reader.readLine())) {
		        outputBuilder.append(string).append('\n');
		      }
		    }
		    return outputBuilder.toString();
		  }	
	

}
